package cn.harry.modular.portrait.controller;

import cn.harry.common.annotation.SysLog;
import cn.harry.common.api.R;
import cn.harry.common.enums.BusinessType;
import cn.harry.modular.portrait.domain.User;
import cn.harry.modular.portrait.excel.UserImportListener;
import cn.harry.modular.portrait.service.UserService;
import cn.harry.modular.portrait.vo.EchartsOptionVO;
import cn.harry.modular.portrait.vo.PopulationAttributeIndicatorsVO;
import cn.harry.modular.portrait.vo.PortraitUserVO;
import cn.harry.modular.portrait.vo.RfmUserVO;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 用户前端控制层
 *
 * @author harry
 * @公众号 Harry技术
 */
@Tag(name = "用户接口")
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;

    /**
     * 分页查询列表
     */
    @Operation(summary = "分页查询")
    @PreAuthorize("@ss.hasPermission('portrait_user_page')")
    @GetMapping(value = "/page")
    public R<IPage<User>> page(@ParameterObject Page<User> page, @ParameterObject User entity) {
        return R.success(userService.page(page, Wrappers.lambdaQuery(entity)));
    }

    /**
     * 根据id获取详情
     */
    @Operation(summary = "根据id获取详情")
    @PreAuthorize("@ss.hasPermission('portrait_user_get')")
    @GetMapping(value = "/{id}")
    public R<User> getById(@PathVariable Long id) {
        return R.success(userService.getById(id));
    }

    /**
     * 新增
     */
    @Operation(summary = "新增")
    @PreAuthorize("@ss.hasPermission('portrait_user_add')")
    @SysLog(title = "portrait_user", businessType = BusinessType.INSERT)
    @PostMapping
    public R<Integer> save(@RequestBody User entity) {
        return userService.save(entity) ? R.success() : R.failed();
    }

    /**
     * 更新
     */
    @Operation(summary = "更新")
    @PreAuthorize("@ss.hasPermission('portrait_user_edit')")
    @SysLog(title = "portrait_user", businessType = BusinessType.UPDATE)
    @PutMapping
    public R<Integer> update(@RequestBody User entity) {
        return userService.updateById(entity) ? R.success() : R.failed();
    }

    /**
     * 删除
     */
    @Operation(summary = "删除")
    @PreAuthorize("@ss.hasPermission('portrait_user_del')")
    @SysLog(title = "portrait_user", businessType = BusinessType.DELETE)
    @DeleteMapping(value = "/{ids}")
    public R<Integer> deleteByIds(@Parameter(description = "多个以英文逗号(,)拼接") @PathVariable Long[] ids) {
        return userService.removeBatchByIds(Arrays.asList(ids)) ? R.success() : R.failed();
    }

    @Operation(summary = "用户模板")
    @SysLog(title = "用户模板", businessType = BusinessType.EXPORT)
    @GetMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException {
        EasyExcel.write(response.getOutputStream(), PortraitUserVO.class).sheet("用户模板").doWrite(ArrayList::new);
    }


    @Operation(summary = "用户导入")
    @PostMapping("import")
    public R importUser(MultipartFile file) {
        String filename = file.getOriginalFilename();
        if (StrUtil.isEmpty(filename)) {
            throw new RuntimeException("请上传文件!");
        }
        if ((!StringUtils.endsWithIgnoreCase(filename, ".xls") && !StringUtils.endsWithIgnoreCase(filename, ".xlsx"))) {
            throw new RuntimeException("请上传正确的excel文件!");
        }
        InputStream inputStream;
        try {
            UserImportListener importListener = new UserImportListener(userService);
            inputStream = new BufferedInputStream(file.getInputStream());
            ExcelReaderBuilder builder = EasyExcel.read(inputStream, PortraitUserVO.class, importListener);
            builder.doReadAll();
            //返回读取的内容
            return R.success(importListener.getList());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success("操作成功");
    }


    // 用户分析
    // 人口属性指标 购物性别女 购物性别男 近30日新增用户 昨日购买用户
    @Operation(summary = "人口属性指标")
    @GetMapping("/populationAttributeIndicators")
    public R<PopulationAttributeIndicatorsVO> populationAttributeIndicators() {
        PopulationAttributeIndicatorsVO vo = userService.populationAttributeIndicators();
        return R.success(vo);
    }

    // RFM 用户
    @Operation(summary = "RFM 用户")
    @GetMapping("/rfmUser")
    public R<List<RfmUserVO>> rfmUser() {
        List<RfmUserVO> list = userService.rfmUser();
        return R.success(list);
    }

    // 注册用户数
    @Operation(summary = "注册用户数")
    @GetMapping("/registeredUserCount")
    public R<EchartsOptionVO> registeredUserCount() {

        return R.success(userService.registeredUserCount());
    }

    // 活跃用户数 占比
    @Operation(summary = "活跃用户数")
    @GetMapping("/activeUserCount")
    public R<EchartsOptionVO> activeUserCount() {

        return R.success(userService.activeUserCount());
    }

    // 近30天访问天数
    @Operation(summary = "近30天访问天数")
    @GetMapping("/recent30DaysVisitDays")
    public R<EchartsOptionVO> recent30DaysVisitDays() {

        return R.success(userService.recent30DaysVisitDays());
    }


}
